<template>
  <view class="ithui-content">
    <view class="withdraw">
      <view class="withdraw-head">
        <view class="withdraw-head-to">到账渠道</view>
        <view class="withdraw-head-way">
          <view class="withdraw-head-way-1" @click="withdraw">
            <!-- <image class="way-icon" src="/static/money.png"></image> -->
            <text class="way-text">推广提现</text>
          </view>
          <view class="withdraw-head-way-2">后台审核后到账</view>
        </view>
      </view>
      <view>
        <u-select
          v-model="formData.wechat_user_bank_id"
          :list="bankList"
          label="选择银行卡"
          placeholder="请选择银行卡"
          @change="onChange"
        ></u-select>
      </view>
      <view class="withdraw-body">
        <text>提现金额</text>
        <view class="input-money">
          <text class="rmb">￥</text>
          <u--input
            placeholder="请输入提现金额"
            border="none"
            v-model="extract"
            :formatter="formatNumber"
            type="digit"
          ></u--input>
          <!-- <input
            v-model.number="extract"
            type="text"
            @focus.prevent="stopKeyborad"
            class="t-input"
          /> -->
        </view>

        <view class="info-money">
          <view v-if="isOut">
            <text class="info-money-num" style="color: #ff1e0f">
              输入金额超过可提现余额，账户余额{{ pool }}元
            </text>
          </view>
          <view v-else>
            <text class="info-money-num">当前可提现余额{{ pool }}元，</text>
            <text class="info-money-all" @click="getAll">全部提现</text>
            <view>
              <text style="color: red"
                >温馨提示：您的余额需≥{{
                  userInfo.withdraw_min
                }}元才能操作提现哦！</text
              >
            </view>
          </view>
        </view>
        <view>
          <button @click="handleShowModel">提现</button>
        </view>
      </view>
      <u-modal
        :show="showModal"
        title="提现确认"
        show-cancel-button
        cancel-text="我再想想"
        confirm-color="#ff1e0f"
        confirm-text="确认提现"
        @confirm="getMoney"
        @cancel="showModal = false"
      >
        <view class="slot-content">
          <rich-text :nodes="content"></rich-text>
        </view>
      </u-modal>
    </view>
  </view>
</template>

<script setup>
import { ref, nextTick } from "vue";
import { getIncomeInfo, putWithdrawIncome, getSaveIndex } from "@/api/userInfo";
import { onShow } from "@dcloudio/uni-app";
import { showLoading, showToast } from "@/utils/toast";
const userInfo = ref({
  withdraw_min: "",
});
onShow(async () => {
  await getSaveIndex().then((res) => {
    console.log(res.data);
    // bankList.value = res.data;
    bankList.value = res.data.map((item) => ({
      text: `${item.bank_name} (${item.bank_no.slice(-4)})`, // 显示银行名+尾号4位
      value: item.id, // 用银行记录ID作为value
    }));
    console.log(bankList.value);
  });
  return await getIncomeInfo().then((res) => {
    pool.value = res.data.income;
    userInfo.value = res.data;
  });
});

// wechat_user_bank_id
// 响应式数据
const pool = ref(0);
const extract = ref();
const serviceFee = ref(0);
const showModal = ref(false);
const isOut = ref(false);
const isPost = ref(false);
const lowest = ref(0);
const fee = ref(0);
const money = ref("");
const realMoney = ref("");
const isRefuse = ref(false);
const content = ref("");
const bankList = ref([]);
const formData = ref({ num: "", wechat_user_bank_id: "" });
// 全部提现
const getAll = () => {
  extract.value = pool.value;
  checkMoney();
};
// 校验金额
const checkMoney = () => {
  if (extract.value != 0) {
    console.log(extract.value <= pool.value);
    if (extract.value <= pool.value) {
      isOut.value = false;
      isPost.value = true;
    }
    if (!formData.value.wechat_user_bank_id) {
      showToast("请选择银行卡");
      return;
    }
    if (extract.value > pool.value) {
      isOut.value = true;
      isPost.value = false;
      return;
    }
  }
  if (isNaN(parseFloat(extract.value))) {
    showToast("输入金额不合法");
  }
};

// 显示确认弹窗
const handleShowModel = () => {
  if (isRefuse.value) return;
  checkMoney();
  if (!isPost.value) return;

  money.value = extract.value;
  // // 计算服务费（保留两位小数）
  serviceFee.value = Number((extract.value * (fee.value / 100)).toFixed(2));
  // 计算实际到账金额
  realMoney.value = Number((extract.value - serviceFee.value).toFixed(2));
  content.value = `
    <p>实际到账：<em style="font-style:normal;color:#ff1e0f">${realMoney.value} 元</em></p>
  `;
  // 构建弹窗内容
  // content.value = `
  //   <p>提现金额：<em style="font-style:normal;color:#ff1e0f">${money.value} 元</em></p>
  //   <p>实际到账：<em style="font-style:normal;color:#ff1e0f">${realMoney.value} 元</em></p>
  //   <p>服务费用：<em style="font-style:normal;color:#ff1e0f">${serviceFee.value} 元</em></p>
  //   <p>服务费率：<em style="font-style:normal;color:#ff1e0f">${fee.value}%</em></p>
  // `;

  showModal.value = true;
};

// 确认提现
const getMoney = async () => {
  formData.value.num = extract.value;
  if (isRefuse.value) return;
  isRefuse.value = true;

  return await putWithdrawIncome(formData.value).then((res) => {
    console.log(res);
    if (res.code == 10000) {
      getIncomeInfo().then((res) => {
        pool.value = res.data.income;
      });
      showToast("提现申请已提交，等待审核");
      showModal.value = false;
    } else {
      isRefuse.value = false;
    }
  });
};
// 格式化函数：只保留两位小数
const formatNumber = (value) => {
  // 清除非数字和小数点的字符
  value = value.replace(/[^\d.]/g, "");
  // 限制只能有一个小数点
  value = value.replace(/\.{2,}/g, ".");
  // 只保留两位小数（小数点后超过两位则截断）
  value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
  // 去除整数部分前的多余0（如 "000123" → "123"）
  value = value.replace(/^0+(\d)/, "$1");
  // 处理纯小数点的情况（如 "." → ""）
  if (value === ".") value = "";
  return value;
};
const onChange = (e) => {
  formData.value.wechat_user_bank_id = e;
  isRefuse.value = false;
};
const withdraw = () => {
  uni.navigateTo({
    url: `/pages/user/my_jiLu`,
  });
};
</script>

<style lang="scss" scoped>
// 样式穿透使用 :deep()
:deep(.u-modal__content) {
  justify-content: flex-start;
}

.ithui {
  &-content {
    .withdraw {
      padding: 40rpx;

      &-head {
        background-color: #f7f7f7;
        display: flex;
        align-content: center;
        padding: 40rpx 60rpx;
        font-size: 28rpx;

        &-to {
        }

        &-way {
          display: flex;
          flex-direction: column;
          align-content: center;
          margin-left: 40rpx;

          &-1 {
            color: #576b95;
            margin-bottom: 20rpx;
            display: flex;
            align-items: center;

            .way-icon {
              width: 36rpx;
              height: 36rpx;
              margin-right: 10rpx;
            }
          }

          &-2 {
            color: #acacac;
            font-size: 26rpx;
          }
        }
      }

      &-body {
        background-color: #fff;
        padding: 40rpx 60rpx;
        font-size: 28rpx;
        margin-bottom: 20rpx;

        .input-money {
          display: flex;
          align-content: center;
          font-weight: 600;
          border-bottom: 1rpx solid #eaeef1;
          padding: 20rpx 0;

          .rmb {
            font-size: 2em;
            margin-top: 20rpx;
          }

          .t-input {
            height: 1.9em;
            font-size: 2.5em;
            border: none;
            margin-left: 3.5%;
            outline: none;
            flex: 1;
          }
        }

        .info-money {
          margin-top: 20rpx;
          font-size: 24rpx;
          margin-bottom: 40rpx;

          &-num {
            color: #b2b2b2;
          }

          &-all {
            color: #576b95;
            cursor: pointer;
          }
        }

        .tx {
          button {
            width: 100%;
            height: 80rpx;
            border-radius: 40rpx;
            background-color: #f5f5f5;
            color: #b2b2b2;
            font-size: 30rpx;
          }
        }

        .tx-active {
          button {
            background: #07c160;
            color: #fff;
          }
        }
      }

      .keyboard {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        background: #ebebeb;
        display: flex;
        justify-content: center;
        z-index: 2;
        flex-wrap: wrap;
        transition: all 0.2s ease-in 0.2s;
      }

      .active {
        bottom: -400rpx;
      }

      .keyboard-item {
        box-sizing: border-box;
        width: 33.333%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background: #fff;
        font-size: 40rpx;
        color: #333;
        height: 100rpx;
        border: 1rpx solid #ebebeb;
        border-top: none;
        border-left: none;
      }

      .hide {
        opacity: 0;
      }

      .delte {
        background: none;
      }

      .delte image {
        width: 60rpx;
        height: 60rpx;
      }

      .isIphone {
        padding-bottom: 68rpx !important;
      }
    }
  }
}
</style>
